<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/8/12
 * Time: 13:58
 */
declare (strict_types = 1);

namespace app\index\middleware;


use think\exception\ValidateException;

class ParamValidate
{
    /**
     *
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //获取当前参数
        $params = $request->param();
        if(!empty($params)) {
            $mode = request()->method();
            if (strtolower($mode) == 'post') {
                $scene = "save";
            } elseif (strtolower($mode) == 'get') {
                $scene = "index";
            } elseif (strtolower($mode) == 'delete') {
                $scene = "delete";
            } elseif (strtolower($mode) == 'put') {
                $scene = "update";
            } else {
                $scene = "";
            }
            $validate = 'app\validate\\' . ucwords(explode('/', request()->pathinfo())[0]) . 'Validate';
            if (class_exists($validate)) {
                try {
                    $v = new $validate;
                    $v->scene($scene)->failException(true)->check($params);
                    if ($scene) {
                        $t = $v->scene[$scene];
                        foreach ($params as $key =>$val) {
                            if (!in_array($key, $t)) {
                                unset($params[$key]);
                            }
                        }
                    }
                } catch (ValidateException $e) {
                    return fail($e->getError());
                }
            }
            $request->data = $params;
        }
        return $next($request);
    }
}